package ar.edu.unlu.sistemas.movirdroid.business.msg;

import java.util.List;
import java.util.StringTokenizer;

import ar.edu.unlu.sistemas.movirdroid.android.AppService;
import ar.edu.unlu.sistemas.movirdroid.business.module.TestModule;
import ar.edu.unlu.sistemas.movirdroid.business.net.tcp.TCPConnection;
import ar.edu.unlu.sistemas.movirdroid.business.util.Logger;
import ar.edu.unlu.sistemas.movirdroid.business.util.StringUtils;
import ar.edu.unlu.sistemas.ws.business.Message;
import ar.edu.unlu.sistemas.ws.business.QueryResultVO;

public class MessageInterpreter {
	
	public static void interpretMessage(TCPConnection connection, Message msg) {
		if ("QUERY".equals(msg.getType())) {
			List<QueryResultVO> result = (List<QueryResultVO>) AppService.instance.processQueryRemote(msg.getQuery());
			Message response = new Message();
			response.setType("QUERY_RESPONSE");
			response.setResult(result);
			connection.send(response);
		} else if ("PRUEBA".equals(msg.getType())) {
			Message response = new Message();
			response.setType("TUMOR");
			connection.send(response);
		}  else connection.close();
	}
	
	public static String interpretMessage(String plainMessage) {
		String result;
		if(!StringUtils.esStringVacioONull(plainMessage)) {
			StringTokenizer st = new StringTokenizer(plainMessage,"|");
			String temp;
			if (st.hasMoreTokens()) {
				temp = st.nextToken();
				try {
					int code = new Integer(temp).intValue();
					boolean is300 = false;
					switch (code) {
					case 300:
						is300 = true;
					case 200:
						Integer nFiles = null;
						if (st.hasMoreTokens()) {
							temp = st.nextToken();
							nFiles = new Integer(temp).intValue();
						}
						long[] retArr = TestModule.reIndexFiles(nFiles);
						if (is300) {
							result = null;
							result = TestModule.queryTest(nFiles);
						} else {
							result = "OK|"+String.valueOf(retArr[2])+"|"+String.valueOf(retArr[0])+"|"+
								String.valueOf(retArr[1])+"|"+String.valueOf(TestModule.vocabularySize());
						}
						break;
					default:
						result = "ERROR: Codigo de mensaje invalido";
					}
				} catch (Exception e) {
					result = "ERROR: En la indexacion o recepcion del mensaje";
					Logger.logError(MessageInterpreter.class.getName(), result, e);
				}
			} else {
				result = "ERROR: Mensaje sin codigo";
			}
		} else {
			result = "ERROR: Mensaje vacio";
		}
		return result;
	}

}
